package com.zyx.flinkdemo.sql.window.tableapi.time;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Slide;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

/**
 * @author zyx
 * @since 2021/5/29 20:16
 * desc: 基于 处理时间 的 滑动时间窗口 案例
 */
public class SlideProcessTimeDemo {
    public static void main(String[] args) throws Exception {
        // 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 读取端口数据创建流并转换每一行数据为JavaBean对象
        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env.socketTextStream("linux201", 7777)
                .map(line -> {
                    String[] split = line.split(",");
                    return new WaterSensor(split[0],
                            Long.parseLong(split[1]),
                            Integer.parseInt(split[2]));
                });
        // 将流转换为表并指定处理时间
        Table table = tableEnv.fromDataStream(waterSensorDs,
                $("id"),
                $("ts"),
                $("vc"),
                $("pt").proctime());
        // 开滑动窗口计算WordCount
        Table result = table.window(Slide.over(lit(5).seconds())
                .every(lit(2).seconds())
                .on($("pt"))
                .as("ws"))
                .groupBy($("id"), $("ws"))
                .select($("id"), $("id").count());
        // 将结果表转换为流进行输出
        tableEnv.toAppendStream(result, Row.class).print();
        // 执行
        env.execute();
    }
}
